<template>
  <t-w-info-box class="info-box" :info="twInfo" @refresh="handleClickRefresh"></t-w-info-box>
  <!--    展示板-->
  <div class="part">
<!--    <EnglishShowboard   :text-list="textList" :curr-index="currTextIndex" :font-size="35"></EnglishShowboard>-->
    <Showboard :text-list="textList" :curr-index="currTextIndex" :font-size="80"></Showboard>
  </div>

  <!--    键盘-->
  <div style="font-size: 10px;" class="flex-row-center part">
    <KeyBoard :config="kbConfig" :active-keys="computedAdviceKeyList"
              @change="handleKeyChange"
              v-show="globalSetting.showKeyboard"></KeyBoard>
  </div>
  <!--    进度条-->
  <div class="text-practice-progress flex-row-center">
    <y-progress color="var(--theme-color)"
                width="100%"
                :percent="currTextIndex/resultList.length*100"
                height="8"
                v-show="globalSetting.showProgress"
    ></y-progress>
  </div>
</template>

<script setup lang="ts">


import KeyBoard from "@/components/keyboard/KeyBoard.vue";
import {computed, ref, watch, defineProps, defineEmits} from "vue";

import globalSettingStore from "@/store/globalSettingStore";
import {RecordItem, RecordStatus, TWInfo} from "@/ts/record";
import {KeyboardEventConfig, KeyboardEventMode} from "@/ts/keyboard";
import YProgress from "@/components/progress/YProgress.vue";
import {speakEnglish,stopSpeak} from "@/utils/VoiceUtil";
import useTimer from "@/hooks/useTimer"
import {ElMessage} from "element-plus";
import TWInfoBox from "@/components/infobox/TWInfoBox.vue";
import EnglishShowboard from "@/components/showboard/EnglishShowboard.vue";
import {Tollgate} from "@/ts/scheme";
import Showboard from "@/components/showboard/Showboard.vue";

let props=defineProps<{
  tollgate:Tollgate
}>()
let emit=defineEmits<{
  (e:"end",val:RecordItem[]):void
}>()
// 特殊字符处理映射
const specialValueMap={
  ' ':'space',
  '\n':'enter',
}
// 文字列表
let textList=ref<RecordItem[]>([])
let resultList = ref<RecordItem[]>([])
// 文字索引
let currTextIndex = ref(0)
// 全局设置 store
const {globalSetting}=globalSettingStore()

// 键盘配置
const kbConfig:KeyboardEventConfig={
  include:[',','.','?','enter'],
  mode:KeyboardEventMode.SIMPLE
}
// 打字信息
let twInfo=ref<TWInfo>({
  currNum: 0,
  errorNum: 0,
  rightNum: 0,
  time: 0,
  total: 0
})
const defaultTwInfo={
  currNum: 0,
  errorNum: 0,
  rightNum: 0,
  time: 0,
  total: 0
}
// 定时器
let {time,startTime,stopTime} = useTimer();
startTime()


watch(()=>props.tollgate,(newV)=>{
  init()
},{immediate:true})



// 监测当前索引变化
watch(currTextIndex,(newV)=>{
  let len=props.tollgate.content.length
  if(newV === len){
    end()
    return
  }

  if( newV < twInfo.value.total){
    twInfo.value.currNum =newV
  }
})
// 监测定时
watch(time,(newV)=>{
  twInfo.value.time=newV
})

function init(){
  // 索引归零
  currTextIndex.value=0
  // 显示文字归零
  textList.value=getRecordItemList(props.tollgate.content)
  // 记录结果归零
  resultList.value=[]


  twInfo.value=defaultTwInfo
  stopTime()
  startTime()
}

function getRecordItemList(content:string): Array<RecordItem> {
  let resultList: Array<RecordItem> = []
  if (content) {
    for (let ch of content) {
      resultList.push({
        value:ch,
        status:RecordStatus.VOID
      })
    }
  }
  return resultList
}



// 计算当前提示字符
let computedAdviceKeyList = computed(()=>{

  let len = textList.value.length
  let index=currTextIndex.value < len ? currTextIndex.value:len-1
// 当前需要输入的字符
  let text=textList.value[index].value
  // 如果全局设置提示为false
  if(!globalSetting.showKeyboardAdvice){
    return
  }
  // 特殊处理空格
  if(text.trim() === ''){
    text="space"
  }
  // 键盘提示键
  return [text]
})



// 按键修改事件
let handleKeyChange = (letter:string) => {

  if (currTextIndex.value < textList.value.length) {
    // 输入内容
    let name = letter;
    // 正确内容
    let textItem = textList.value[currTextIndex.value];
    // 小写化
    let rightText = textItem.value.toLowerCase();
    let inputText = name.toLowerCase();

    // 判断正确与否
    // 特殊字符处理
    if(specialValueMap[rightText] === inputText){
      success()
    }else{
      // 成功
      if(rightText === inputText){
        success()
      }else{
        error()
      }

    }
  }
}
// 获取当前索引指向的RecordItem
function getCurrItem():RecordItem{
  let index = hasNext()?currTextIndex.value:textList.value.length-1
  return textList.value[index];
}
function hasNext():boolean{
  return currTextIndex.value < textList.value.length
}
function success(){
  let currItem=getCurrItem()
  if(currItem.status === RecordStatus.VOID){
    resultList.value.push({
      status: RecordStatus.SUCCESS,
      value: currItem.value
    })
  }
  currItem.status=RecordStatus.SUCCESS
  twInfo.value.rightNum++
  // 指针前移
  currTextIndex.value++
  if(globalSetting.playAudio){
    stopSpeak()
    speakEnglish(currItem.value)
  }

}
function error(){
  let currItem=getCurrItem()
  twInfo.value.errorNum++
  // 记录结果
  resultList.value.push({
    status: RecordStatus.ERROR,
    value: currItem.value
  })
  // 失败
  currItem.status=RecordStatus.ERROR
}

function end(){
  // TODO emit("end",完成记录Record)
  // 停止计时器
  stopTime()
  // 发送end事件
  emit('end',resultList.value)
}
function handleClickRefresh(){
  init()
  ElMessage({
    type:"success",
    message:"刷新成功"
  })
}

</script>

<style scoped lang="less">
.part {
  margin-bottom: 40px;
  width: 60%;
}
.text-practice-progress{
  position: fixed;
  width: 90%;
  transform: translateX(-50%);
  bottom: 0;
  left: 50%;
}
</style>